package com.bridgeintelligent.tag.user.mgmt.web;

import com.bridgeintelligent.tag.constants.ExceptionCodes;
import com.bridgeintelligent.tag.user.mgmt.entity.Result;
import com.bridgeintelligent.tag.user.mgmt.entity.UserCodes;
import com.bridgeintelligent.tag.user.mgmt.exception.UserException;
import com.bridgeintelligent.tag.user.mgmt.pojo.User;
import com.bridgeintelligent.tag.user.mgmt.service.UserMgmtService;
import com.bridgeintelligent.tag.user.mgmt.util.POIUtils;
import com.bridgeintelligent.tag.user.query.service.RoleQueryService;
import com.bridgeintelligent.tag.user.query.service.UserQueryService;
import com.bridgeintelligent.tag.utils.PasswordHelper;
import com.bridgeintelligent.tag.webserver.security.TagSecurityHelper;
import com.bridgeintelligent.tag.webserver.security.aes.AesUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Api(tags = "用户管理")
@RestController
@RequestMapping("/api/user")
@Slf4j
public class UserMgmtController {

    @Autowired
    private UserMgmtService userMgmtService;
    @Autowired
    private UserQueryService userQueryService;
    @Autowired
    private RoleQueryService roleQueryService;

    private static Logger logger = LoggerFactory.getLogger(UserMgmtController.class);



    /**
     * 新增用户
     *
     * @return
     */
    @ApiOperation("新增用户")
    @PostMapping("/add")
    public Result addUser(@ModelAttribute User user, HttpServletRequest request) {

        try {
            checkId(request);
            User dbUser = userQueryService.findByUserId(user.getUserId());
            //校验用户是否已存在
            if (dbUser != null) {
                throw new UserException(ExceptionCodes.USER_30006);
            }
            //校验密码强弱性
            String pwd = user.getPassword();
            try {
                pwd = AesUtils.aesDecrypt(pwd, AesUtils.AES_KEY);
                Map<String, String> map = PasswordHelper.validPwd(pwd);
                if ("false".equals(map.get("F"))){
                    return new Result(-1, map.get("M"));
                }
                user.setPassword(pwd);
            }catch (Exception e){
                return new Result(-1, "解密失败");
            }

            //新建用户
            userMgmtService.addUser(user);
            return new Result(UserCodes.SUCCESS);
        } catch (UserException e) {
            return new Result(e.getCode(), "操作失败");
        }
    }


    /**
     * 删除用户
     *
     * @param userId
     * @return
     */
    @ApiOperation("删除用户")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "path", name = "userId", value = "用户名", required = true)})
    @DeleteMapping("/delete/{userId}")
    public Result deleteUser(@PathVariable String userId,HttpServletRequest request) {
        try{
            checkId(request);
            userMgmtService.deleteUserByUserId(userId);
            return new Result(UserCodes.SUCCESS);
        }catch (UserException e){
            return new Result(e.getCode(),e.getMessage());
        }
    }

    /**
     * 修改用户信息
     *
     * @param user
     * @return
     */
    @ApiOperation("修改用户信息")
    @PostMapping("/update")
    public Result updateUser(@ModelAttribute User user,HttpServletRequest request) {
        try {
            checkId(request);
            updateData(user);
            return new Result(UserCodes.SUCCESS);
        } catch (UserException e) {
            return new Result(e.getCode(), user.getUsername() + "操作失败");
        }
    }

    public void updateData(User user) {
        User dbUser = userQueryService.findByUserId(user.getUserId());
        if (dbUser == null) {
            userMgmtService.addUser(user);
        } else {
            if (StringUtils.isNotEmpty(user.getInstitution())) {
                dbUser.setInstitution(user.getInstitution());
            }
            if (StringUtils.isNotEmpty(user.getName())) {
                dbUser.setName(user.getName());
            }
            if (StringUtils.isNotEmpty(user.getUserPhone())) {
                dbUser.setUserPhone(user.getUserPhone());
            }
            if (StringUtils.isNotEmpty(user.getEmail())) {
                dbUser.setEmail(user.getEmail());
            }
            if (StringUtils.isNotEmpty(user.getRoleId())) {
                dbUser.setRoleId(user.getRoleId());
            }
            userMgmtService.updateUser(user);
        }
    }

    /**
     * 上传文件,批量添加用户
     *
     * @param excelFile
     * @return
     */
    @ApiOperation("文件批量新增用户")
    @PostMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile excelFile) {
        try {
            //读取Excel文件
            List<String[]> list = POIUtils.readExcel(excelFile);
            if (list != null && list.size() > 0) {
                for (String[] strings : list) {
                    User user = new User();
                    String userId = strings[0];
                    if (StringUtils.isEmpty(userId)) {
                        throw new UserException(ExceptionCodes.USER_30007);
                    }
                    user.setUserId(userId);
                    user.setUsername(userId);
                    user.setInstitution(strings[1]);
                    user.setUserPhone(strings[2]);
                    user.setEmail(strings[3]);
                    String roleName = strings[4];
                    String roleId = roleQueryService.findRoleIdByName(roleName);
                    user.setRoleId(roleId);
                    user.setName(strings[5]);
                    user.setPassword(PasswordHelper.encode("123456"));
                    updateData(user);
                }
            }
        } catch (UserException e) {
            return new Result(e.getCode(), e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("上传文件出现异常", "操作失败");
        }
        return new Result(UserCodes.SUCCESS);
    }

    @ApiOperation("修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "userId", value = "用户ID"),
            @ApiImplicitParam(paramType = "query", name = "oldPassword", value = "旧密码"),
            @ApiImplicitParam(paramType = "query", name = "newPassword", value = "新密码"),
            @ApiImplicitParam(paramType = "query", name = "comfirePassword", value = "确认密码")
    })
    @PostMapping("/updatePassword")
    public Result updatePassword(String userId,String oldPassword,String newPassword,String comfirePassword,HttpServletRequest request) {
        try {
            checkId(request);
            return userMgmtService.updatePassword(userId,oldPassword,newPassword,comfirePassword);
        }catch (UserException e){
            return new Result(e.getCode(),"操作失败");
        }
    }



    /**
     * 用户信息同步
     *
     * @return
     */
    @ApiOperation("用户信息同步")
    @PostMapping("/synch/userInfo")
    public Result userInfo(@RequestBody String jsonStr) {
        logger.info("用户信息json:{}",jsonStr);
        try {
            return userMgmtService.synchUserInfo(jsonStr);
        } catch (UserException e) {
            logger.info("用户信息同步失败--：{}",e);
            return new Result(-1, "操作失败");
        }
    }

    @ApiOperation("根据身份证信息查询对应的客户号")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "card_id", value = "身份证号码")
    })
    @PostMapping("/findCustNoByCardId")
    public Result findCustNoByCardId(String card_id) {
        logger.info("身份证号查询客户号服务："+card_id);
        try {
            return userMgmtService.findCustNoByIdCard(card_id);
        }catch (Exception e){
            logger.info("查询失败",e);
            return new Result(-1,"查询失败");
        }
    }

    public void checkId(HttpServletRequest request){
        String cardId = request.getHeader("identity_flag");
        User user = TagSecurityHelper.currentUser();
        if (StringUtils.isEmpty(cardId) || !cardId.equals(user.getUserId())){
            throw new UserException(ExceptionCodes.USER_30008);
        }
    }


    @ApiOperation("读取服务器上的文件")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "filePath", value = "读取服务器上的文件")
    })
    @PostMapping("/readPath")
    public Result readPath(String filePath) {
        logger.info("读取服务器上的文件："+filePath);
        try {
            File file = new File(filePath);
            BufferedReader input = new BufferedReader(new FileReader(file));
            String line = null;
            while ((line = input.readLine())!= null){
                logger.info(line+"的长度是："+line.length());
            }
            return new Result(0,"操作成功");
        }catch (Exception e){
            logger.info("查询失败",e);
            return new Result(-1,"查询失败");
        }
    }

    @ApiOperation("获取数据空间站的访问令牌")
    @GetMapping("/getToken")
    public Result getToken() {
        logger.info("-----------------获取数据空间站的访问令牌--------");
        try {
            return userMgmtService.getDataToken();
        } catch (UserException e) {
            return new Result(-1,"获取数据空间站访问令牌失败"+e.getMessage());
        }
    }

}